package com.bigscreen.service.impl;

import com.bd1904.conf.Constants;
import com.bigscreen.dao.ShopRankDao;
import com.bigscreen.mapper.ShopInfoMapper;
import com.bigscreen.pojo.ShopInfoDTO;
import com.bigscreen.pojo.ShopRank;
import com.bigscreen.service.ShopRankService;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.TreeSet;

@Service
public class ShopRankServiceImpl implements ShopRankService {

    @Autowired
    private ShopRankDao srDao;

    @Autowired
    private ShopInfoMapper shopMapper;

    @Override
    public String shopRankTop(int topN, boolean asc) {
        //第一步，获取zset集合的长度
        Long length = srDao.length(Constants.JEDIS_CALC_SHOP_AMT);
        //第二步,获取需要的topN的数据，zset按照score从小到大排序，所以topN需要倒叙
        Set<String> members = null;
        if(asc){
            members = srDao.zrange(Constants.JEDIS_CALC_SHOP_AMT,
                    0,topN);
        }else{
            members = srDao.zrange(Constants.JEDIS_CALC_SHOP_AMT,
                    length.intValue()-topN,length.intValue());
        }

        //第三步：根据这些member获取对应的score得分
        TreeSet<ShopRank> treeSet = new TreeSet<ShopRank>();
        for (String member:members) {
            Double score = srDao.score(Constants.JEDIS_CALC_SHOP_AMT,member);
            ShopRank shopRank = new ShopRank();
            shopRank.setShopAmt(score);

            Long ShopId = Long.valueOf(member);
            shopRank.setShopId(ShopId);
            shopRank.setShopName(shopMapper.selectByPrimaryKey(ShopId).getShopName());
            shopRank.setAsc(asc);
            treeSet.add(shopRank);
        }
        //第四步：member 与 score 组装json
        JSONArray jsonArray = new JSONArray(treeSet);
        System.out.println(jsonArray);
        return jsonArray.toString();
    }
}
